<?php

namespace App\Http\Controllers;

use App\Models\StorageConfig;
use App\Services\StorageService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;

class UploadController extends Controller
{
    protected $storageService;

    public function __construct(StorageService $storageService)
    {
        $this->middleware('auth.api');
        $this->storageService = $storageService;
    }

    /**
     * 上传图片
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function image(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:5120', // 5MB
            'storage_id' => 'nullable|exists:storage_configs,id',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator);
        }

        try {
            $file = $request->file('file');
            $extension = $file->getClientOriginalExtension();
            $filename = date('YmdHis') . '_' . Str::random(10) . '.' . $extension;
            
            // 获取存储配置
            $storageConfig = null;
            if ($request->has('storage_id')) {
                $storageConfig = StorageConfig::find($request->storage_id);
            }
            
            // 临时保存文件
            $tempPath = $file->storeAs('temp', $filename, 'local');
            $fullTempPath = storage_path('app/' . $tempPath);
            
            // 使用存储服务上传
            $result = $this->storageService->upload($fullTempPath, $filename, $storageConfig);
            
            // 删除临时文件
            @unlink($fullTempPath);

            return $this->success([
                'url' => $result['url'],
                'path' => $result['path'],
                'filename' => $file->getClientOriginalName(),
                'size' => $file->getSize(),
                'mime_type' => $file->getMimeType(),
                'storage_type' => $result['type'],
            ], '上传成功');
        } catch (\Exception $e) {
            return $this->error('上传失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 上传文件
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function file(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|file|max:10240', // 10MB
            'storage_id' => 'nullable|exists:storage_configs,id',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator);
        }

        try {
            $file = $request->file('file');
            $extension = $file->getClientOriginalExtension();
            $filename = date('YmdHis') . '_' . Str::random(10) . '.' . $extension;
            
            // 获取存储配置
            $storageConfig = null;
            if ($request->has('storage_id')) {
                $storageConfig = StorageConfig::find($request->storage_id);
            }
            
            // 临时保存文件
            $tempPath = $file->storeAs('temp', $filename, 'local');
            $fullTempPath = storage_path('app/' . $tempPath);
            
            // 使用存储服务上传
            $result = $this->storageService->upload($fullTempPath, $filename, $storageConfig);
            
            // 删除临时文件
            @unlink($fullTempPath);

            return $this->success([
                'url' => $result['url'],
                'path' => $result['path'],
                'filename' => $file->getClientOriginalName(),
                'size' => $file->getSize(),
                'mime_type' => $file->getMimeType(),
                'storage_type' => $result['type'],
            ], '上传成功');
        } catch (\Exception $e) {
            return $this->error('上传失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 删除文件
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        $request->validate([
            'path' => 'required|string',
            'storage_id' => 'nullable|exists:storage_configs,id',
        ]);

        try {
            // 获取存储配置
            $storageConfig = null;
            if ($request->has('storage_id')) {
                $storageConfig = StorageConfig::find($request->storage_id);
            }
            
            // 使用存储服务删除
            $result = $this->storageService->delete($request->path, $storageConfig);
            
            if ($result) {
                return $this->success(null, '删除成功');
            }

            return $this->error('删除失败', 500);
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage(), 500);
        }
    }
}

